from django.db.models.signals import pre_delete
from django.dispatch import receiver
from django.contrib.contenttypes.models import ContentType

from .models import AuditManagement

@receiver(pre_delete)
def cleanup_audit_relations(sender, instance, **kwargs):
    """
    When any model instance is deleted, clean up related AuditManagement objects
    """
    # Skip if the sender is AuditManagement to avoid recursive deletion
    if sender == AuditManagement:
        return
        
    content_type = ContentType.objects.get_for_model(sender)
    
    # Delete related AuditManagement objects
    AuditManagement.objects.filter(
        content_type=content_type,
        object_id=instance.pk
    ).delete()
